public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
//        System.out.println(-201 % 10);
        Solution solution = new Solution();
//        int ret = solution.reverse(-23534636);
//        int ret = solution.reverse(-23534636);
        int ret = solution.reverse(-1563847412);
        System.out.println(ret);
    }
}


class Solution {
    //leetcode题解思路，更为简单
    public int reverse(int x) {
        int max = 0x7FFFFFFF;
        int min = 0x80000000;

        int ret = 0;
        while (x != 0){
            if(Math.abs(x) < 10){
                if (ret > max / 10 || ret == max / 10 && x > max % 10){
                    return 0;
                }
                else if(ret < min / 10 || ret == min / 10 && x < min % 10){
                    return 0;
                }
            }
            ret = ret * 10 + x % 10;
            x = x / 10;
        }
        return ret;
    }
}


//个人解法，较为复杂
class Solution1 {
    public int reverse(int x) {
        if(x == 0){
            return 0;
        }

        boolean sign = x < 0;

        int max[] = toArray(0x7FFFFFFF);
        int min[] = toArray(0x80000000);

        int reversed[] = reverse(toArray(x));
        if((sign && comp(reversed, max) <= 0) || (!sign && comp(reversed, min) <= 0)){
            return array2Int(reversed, sign);
        }

        return 0;
    }

    int[] toArray(int x){
        boolean sign = x < 0;
        int temp = x;
        int a[] = new int[10];
        int i = a.length - 1;
        while(temp != 0){
            a[i] = temp % 10;
            if (sign) a[i] *= -1;
            temp /= 10;
            i--;
        }
        return a;
    }

    int comp(int[] a1, int[] a2){
        for(int i = 0; i < a1.length; i++){
            if (a1[i] > a2[i]) return 1;
            else if(a1[i] < a2[i]) return -1;
        }
        return 0;
    }

    int array2Int(int[] a, boolean sign){
        int x = 0;
        int offset = 0;
        while (a[offset] == 0) offset++;
        for(; offset < a.length; offset++) {
            x = x * 10 + a[offset];
        }
        if(sign) x = -x;
        return x;
    }

    int[] reverse(int[] a){
        int[] ret = new int[10];

        int i = 0;
        while (i < a.length && a[i] == 0) i++;
        int j = a.length - 1;
        while (j >= 0 && a[j] == 0) j--;

        for(int k = 0; k < j - i + 1; k++){
            ret[ret.length - k - 1] = a[i + k];
        }
        return ret;
    }
}